package com.kaikeba.controller;

import com.kaikeba.bean.*;
import com.kaikeba.service.LinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HMF on 2021/06/16 14:28
 */
@RestController
public class LinkController {
    @Autowired
    LinkService linkService;

//    @GetMapping("/")
//    public String index() {
//        return "index";
//    }

    /**
     * @return
     */
    @GetMapping("/links")
    public String findAll() {
        List<Data> data = new ArrayList<>();

        List<LinkData> linkDatas = linkService.findAll(); // 数据库查出的每一项

        int tempSort = 0;

        Data d1 = null;

        List<Link> links = null;  // 每个大类里的所有链接

        for (LinkData linkData : linkDatas) {
            int sort = linkData.getTsort();

            if (tempSort != sort) { // 区分每一个大类
                tempSort = sort;

                d1 = new Data();
                d1.setType(linkData.getName());

                links = new ArrayList<>();
                d1.setLinks(links);

                data.add(d1);
            }

            String content = linkData.getContent();
            String title = linkData.getTitle();
            String description = linkData.getDescription();
            int count = linkData.getCount();
            int icon = linkData.getIcon();
            int id = linkData.getLid();
            int lSort = linkData.getLsort();
            int typeId = linkData.getTid();

            // 组合数据
            Link link = new Link(content, count, description, icon, id, sort, title, typeId);
            links.add(link);
        }

        // 组合数据返回需要的结果
        Message msg = new Message();
        msg.setData(data);
        msg.setMsg("查询成功");
        msg.setStatus(0);

        String json = msg.toJSON();

//        ModelAndView mv = new ModelAndView();
//        mv.addObject(json);
//        mv.addObject("msg", "测试模板");
//        mv.setViewName("index");
//
//        return mv;
        return json;
    }

    @GetMapping("/links/{id}")
    public String findById(@PathVariable(value = "id") int id) {
        return linkService.findById(id);
    }

    @GetMapping("/type")
    public String findAllType() {
        String str = "";
        List<Type> types = linkService.findAllType();
        for (Type type : types) {
            str += type.toString() + "   ";
        }
        return str;
    }
}
